package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApAuthor;
import com.heima.article.feign.ArticleFeign;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserEnum;
import com.heima.media.entity.WmUser;
import com.heima.media.feign.MediaFeign;
import com.heima.user.dto.AuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-28
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Autowired
    private IApUserService apUserService;


    @Autowired
    private MediaFeign mediaFeign;

    @Autowired
    private ArticleFeign articleFeign;


    /**
     * 根据状态查询实名认证审核记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult queryByPage(AuthDto dto) {
        //1.构建分页对象
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        //2.构建查询条件
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (ObjectUtils.isNotEmpty(dto.getStatus())) {
            queryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }

        //3.执行查询
        this.page(page, queryWrapper);

        //4.封装响应数据
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }


    /**
     * 管理员人工审核实名认证信息
     *
     * @param dto  认证参数
     * @param type 操作类型 1：通过  2：驳回
     * @return
     */
    @Override
    public ResponseResult auth(AuthDto dto, int type) {
        //1.修改本服务中对应账户信息
        //1.0 根据实名认证记录ID查询
        ApUserRealname apUserRealname = this.getById(dto.getId());
        //1.1 修改实名认证表状态
        if (type == 2) {
            apUserRealname.setStatus(UserEnum.USER_REALNAME_STATUS_FAIL.getVal());
            apUserRealname.setReason(dto.getReason());
            this.updateById(apUserRealname);
            return ResponseResult.errorResult(200, "审核已被驳回");
        }
        //1.2 修改APP用户表状态
        //1.2.1 根据社交用户ID查询APP用户
        ApUser apUser = apUserService.getById(apUserRealname.getUserId());
        //1.2.2 更新状态
        apUser.setIsIdentityAuthentication(true);
        apUser.setFlag(UserEnum.APPUSER_TYPE_WEMEDIA.getVal());
        apUserService.updateById(apUser);

        //1.3 修改实名认证状态
        apUserRealname.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        this.updateById(apUserRealname);

        //2.远程调用自媒体微服务新增自媒体用户
        WmUser wmUser = createWmuser(apUser);

        //3.远程调用作者微服务新增作者用户
        if (wmUser != null) {
            ApAuthor apAuthor = createApthor(apUser, wmUser);
            if (apAuthor != null) {
                //远程调用自媒体微服务更新自媒体用户逻辑外键：author_id
                wmUser.setApAuthorId(apAuthor.getId());
                mediaFeign.updateWmUser(wmUser);
                return ResponseResult.okResult();
            }
        }
        return ResponseResult.errorResult(500, "审核失败，请联系管理员");
    }


    /**
     * 构建自媒体用户对象；远程保存自媒体用户
     *
     * @param apUser
     * @return 新增后自媒体用户对象
     */
    private WmUser createWmuser(ApUser apUser) {
        //1.创建自媒体用户对象
        WmUser wmUser = new WmUser();
        //1.1 基本属性从社交账户中拷贝
        BeanUtils.copyProperties(apUser, wmUser);

        //1.2 手动赋值的属性
        wmUser.setApUserId(apUser.getId());
        wmUser.setNickname(apUser.getName());
        wmUser.setStatus(UserEnum.USER_REALNAME_STATUS_PASS.getVal());
        wmUser.setType(0);
        wmUser.setScore(0);

        //2.远程调用自媒体微服务完成新增
        ResponseResult<WmUser> responseResult = mediaFeign.saveWmUser(wmUser);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            WmUser data = responseResult.getData();
            return data;
        }
        return null;
    }


    /**
     * 构建作者用户对象；远程保存作者用户
     *
     * @param apUser
     * @return 新增后作者用户对象
     */
    private ApAuthor createApthor(ApUser apUser, WmUser wmUser) {
        //1.创建作者用户对象
        ApAuthor apAuthor = new ApAuthor();
        //1.2 手动赋值的属性
        apAuthor.setName(apUser.getName());
        apAuthor.setType(UserEnum.AUTHOR_TYPE_WEMEDIA.getVal());
        apAuthor.setUserId(apUser.getId());
        apAuthor.setWmUserId(wmUser.getId());

        //2.远程调用文章微服务完成新增
        ResponseResult<ApAuthor> responseResult = articleFeign.saveAuthor(apAuthor);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor data = responseResult.getData();
            return data;
        }
        return null;
    }
}
